package org.dubnation.org.service.impl;

import org.dubnation.base.constants.SystemConstants;
import org.dubnation.base.enums.ResponseCode;
import org.dubnation.base.exception.BusinessException;
import org.dubnation.base.util.SendEmailUtil;
import org.dubnation.base.util.audit.ActiveCode;
import org.dubnation.base.util.audit.ErrorInfo;
import org.dubnation.org.domain.Employee;
import org.dubnation.org.domain.Shop;
import org.dubnation.org.mapper.EmployeeMapper;
import org.dubnation.org.mapper.ShopMapper;
import org.dubnation.org.service.IEmployeeService;
import org.dubnation.base.service.impl.BaseServiceImpl;
import org.dubnation.user.rabbitmq.entity.SendEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.mail.MessagingException;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhu
 * @since 2023-10-27
 */
@Service
@Transactional
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements IEmployeeService {

    @Autowired(required = false)
    private EmployeeMapper mapper;

    @Autowired
    private ActiveCode activeCode;

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate; //将对象存储到redis中需要实现序列化

    @Autowired(required = false)
    private ShopMapper shopMapper;

    @Autowired
    private SendEntity sendEntity;

    @Value("${spring.mail.username}")
    private String senderEmail;

    @Value("${email.send-url.shop-audit.reject-prefix}")
    private String rejectUrl;

    @Value("${email.send-url.shop-audit.pass-prefix}")
    private String passUrl;

    @Override
    public List<String> getPermissionSn(Long id) {
        return mapper.getPermissionSn(id);
    }

    /**
     * 向商家发送商店入驻错误信息，并指定修改的链接地址
     * @param errorInfo
     */
    @Override
    public void shopAuditReject(ErrorInfo errorInfo) throws MessagingException{
        List<Shop> shopList = shopMapper.queryAll();
        shopList.forEach(shop -> {
            if (errorInfo.getShopId().equals(shop.getId())){
                Integer rejectedNum = shop.getRejectedNum();
                rejectedNum++;
                if (rejectedNum > 3){
                    //驳回次数大于3次，拒绝驳回
                    throw new BusinessException(ResponseCode.RESPONSE_CODE_4000010);
                }
                shop.setRejectedNum(rejectedNum);
                shopMapper.updateRejectNum(shop);
            }
        });
        //1.判断该条店铺信息的店长的邮箱是否存在
        Employee admin = mapper.queryById(errorInfo.getAdminId());
        if (Objects.nonNull(admin.getEmail())){
            sendEntity.setFrom(senderEmail);
            sendEntity.setTo(admin.getEmail());
            sendEntity.setSubject(errorInfo.getDetailedMsg());
            String url = rejectUrl + errorInfo.getShopId();
            sendEntity.setContent("请点击链接地址修改店铺信息: <a href='"+ url +"'>'"+ url +"'</a>");
            Boolean sendEmailSuccess = SendEmailUtil.sendEmail(sendEntity);
            if (sendEmailSuccess == true){
                //修改店铺状态为驳回
                shopMapper.updateRejectState(errorInfo.getShopId());
            }
        }else {
            throw new MessagingException(ResponseCode.RESPONSE_CODE_400007.getMessage());
        }
    }

    /**
     * 发送商店审核通过的邮件
     */
    @Override
    public void shopAuditPass(Shop shop) {
        //将激活信息存储到redis中作为参数的传输
        activeCode.setEmployeeId(shop.getAdmin().getId());
        activeCode.setShopId(shop.getId());
        redisTemplate.opsForValue().set(SystemConstants.ACTIVE, activeCode);
        redisTemplate.expire(SystemConstants.ACTIVE, 72L, TimeUnit.HOURS); //设置redis中激活码的有效时间为72小时
        Employee employee = mapper.queryById(shop.getAdmin().getId());
        if (Objects.nonNull(employee.getEmail())){
            sendEntity.setFrom(senderEmail);
            sendEntity.setTo(employee.getEmail());
            sendEntity.setSubject("恭喜您注册的店铺审核通过，您现在可以激活店铺以及管理员账户！");
            String url = passUrl + SystemConstants.ACTIVE;
            String text = "请在72小时之内点击链接" +
                    "<a href='"+ url +"'>'"+ url +"'</a>" + "进行店铺和管理账户激活。";
            sendEntity.setContent(text);
            SendEmailUtil.sendEmail(sendEntity); //发送邮件
        }else {
            throw new BusinessException(ResponseCode.RESPONSE_CODE_400007);
        }
    }
}
